/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.cbcgateway.ipc;

import com.elcom.emocbc.cbcgateway.CbcGateway;
import com.elcom.ipc.synchronize.message.IPC_REQUEST;
import com.elcom.emocbc.common.ipc.transport.IPCServerTrap;
import com.elcom.util.BaseThreadFactory;
import com.elcom.util.Constant;
import java.util.concurrent.*;
import org.jconfig.Configuration;
import org.jconfig.ConfigurationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class CbcGatewayServerTrap extends IPCServerTrap {

    private final Logger logger = LoggerFactory.getLogger(CbcGatewayServerTrap.class);
    private ThreadPoolExecutor executor;

    public CbcGatewayServerTrap(String ipcServerName, String ipcConfigFilePath) throws Throwable {
        super(ipcServerName, ipcConfigFilePath);

        logger.trace("Creating thread pool");
        Configuration config = ConfigurationManager.getConfiguration(Constant.SYS_CONFIG_NAME);
        int corePoolSize = config.getIntProperty("corePoolSize", 15, "processThreadPool");
        int maximumPoolSize = config.getIntProperty("maximumPoolSize", 50, "processThreadPool");
        long keepAliveTime = config.getLongProperty("keepAliveTime", 60000, "processThreadPool");
        int queueSize = config.getIntProperty("queueSize", 10000, "processThreadPool");

        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(queueSize, true);
        RejectedExecutionHandler rejectedExecutionHandler = new IpcRejectedExecutionHandler();
        ThreadFactory threadFactory = new BaseThreadFactory("HttpForwardGroup", "HttpForwardTask");

        executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, workQueue, threadFactory, rejectedExecutionHandler);
        executor.prestartAllCoreThreads();
        logger.trace("Done creating thread pool");
        
        CbcGateway.getInstance().setExecutor(executor);
    }

    @Override
    public void onRequest(IPC_REQUEST request) {
        if (request != null) {
            HttpForwardTask forwardTask = new HttpForwardTask(request);
            executor.execute(forwardTask);
        }
    }
}
